import { CommandDialog } from '@amcax/base';
import { i18n } from '@app-nextmesh/common/utils';
import { ISelectOption } from '@app-nextmesh/components/types';
import { documentV2 } from '@app-nextmesh/domain';
import { useProjectStore } from '@app-nextmesh/store/project';
import {
  IResultNew,
  NMToolBaseCommand,
  NMToolCmdDialogParams,
} from '@app-nextmesh/types';
import { clearModel } from '@app-nextmesh/utils/canvas';
import { Button, Checkbox, Col, Row, Select } from 'antd';
import { useEffect, useState } from 'react';
import styled from 'styled-components';
import { arrowChange } from './drawVectorGraph';

const CheckboxGroup = Checkbox.Group;

const WrapperStyle = styled.div`
  row-gap: 8px;
  width: 350px;
  padding: 0 30px 0 20px;
  padding-bottom: 8px;
  display: flex;
  flex-direction: column;

  .form-dialog_footer {
    width: 100%;
    padding: 8px 0 12px !important;
  }
`;

interface SelectedType {
  model?: string | number;
  step?: string | number;
  field?: string | number;
  resolved?: string | number;
}

function CmdVectorGraphDialog({ title, onClose }: NMToolCmdDialogParams) {
  const projectInfo = useProjectStore((state) => state.projectInfo);
  const [resultsData, setResultsData] = useState([]); // 获取任务uuid
  const [loading, setLoading] = useState(false); // 应用按钮是否在加载中
  const [resultSelected, setResultSelected] = useState<SelectedType>(null); // 记录选的数据源，model, step,field,format,layer,variable等信息
  const [stepData, setStepData] = useState<ISelectOption[]>([]); // 获取步数数据
  const [fieldData, setFieldData] = useState<ISelectOption[]>([]); // 获取场数数据
  const [resultsAllData, setResultsAllData] = useState<IResultNew>(null); // 获取某个任务的相关数据
  const [componentsData, setComponentsData] = useState<string[]>([]); // 获取坐标系数据
  const [resultantData, setResultantData] = useState<string[]>([]); // 获取方向数据
  const [applyShow, setApplyShow] = useState<boolean>(true); // 是否可点击应用

  useEffect(() => {
    const resultsList = [];
    if (projectInfo.results.length !== 0) {
      projectInfo.results.forEach((item) =>
        resultsList.push({ label: item.name, value: item.uuid }),
      );
      initFormData(projectInfo.results[0].uuid);
    }
    setResultsData(resultsList);
  }, [projectInfo]);

  useEffect(() => {
    setApplyShow(true);
    if (componentsData.length !== 0) {
      setApplyShow(false);
    }
    if (resultantData.length !== 0) {
      setApplyShow(false);
    }
  }, [componentsData, resultantData]);

  useEffect(() => {
    return () => {
      clearModel();
    };
  }, [resultSelected]);

  const initFormData = (value) => {
    documentV2.resultInfo(value as string).then((req) => {
      setResultsAllData(req);
      if (req?.solve?.length !== 0) {
        const simulateData = req?.solve;
        const stepList = [];
        simulateData.forEach((item) => {
          stepList.push({
            label: '' + item.step,
            value: item.step,
          });
        });
        const fieldList = [];
        simulateData.forEach((item: any) => {
          if (item.step === 0) {
            item.field.forEach((f) => {
              if (f.type === 'vector') {
                fieldList.push({
                  label: f.name,
                  value: f.name,
                });
              }
            });
          }
        });
        setFieldData(fieldList);
        setResultSelected({
          model: value,
          step: stepList[0].value,
          field: fieldList[0].value,
          resolved: 'global',
        });
        setStepData(stepList);
      }
    });
  };

  // 处理不同下拉选择业务数据
  const handleResultSelectChange = (value: string | number, type: string) => {
    let params = resultSelected;
    switch (type) {
      case 'model':
        params = {
          model: value,
          step: '',
          field: '',
          resolved: 'global',
        };
        initFormData(value);
        setResultSelected({
          ...params,
        });
        break;
      case 'step': {
        params = {
          ...params,
          step: value,
        };
        setResultSelected({
          ...params,
        });
        const fieldList = [];
        resultsAllData.solve.forEach((item) => {
          if (item.step === params.step) {
            item.field.forEach((f) => {
              fieldList.push({
                label: f.name,
                value: f.name,
              });
            });
          }
        });
        setFieldData(fieldList);
        break;
      }
      case 'field':
        params = {
          ...params,
          field: value,
        };
        setResultSelected({
          ...params,
        });
        break;
      case 'resolved':
        params = {
          ...params,
          resolved: value,
        };
        setResultSelected({
          ...params,
        });
        break;
    }
  };

  // 获取后端数据
  const createRendreVectorGraph = async () => {
    const params = {
      step: resultSelected.step,
      frame: resultSelected.step,
      field: resultSelected.field,
      systemType: resultSelected.resolved,
      direction: [...componentsData, ...resultantData],
    };
    const req = await documentV2.renderVector(
      projectInfo.results[0].uuid,
      params,
    );
    if (req?.vector) {
      const verctorReq = req.vector;
      verctorReq.vectorData.forEach((item) => {
        arrowChange(
          verctorReq.point,
          verctorReq.length,
          verctorReq.max,
          verctorReq.min,
          item.value,
          item.direction,
          item.vector,
        );
      });
      setLoading(false);
    }
  };

  return (
    <CommandDialog
      title={title}
      placement='topLeft'
      onClose={onClose}
    >
      <WrapperStyle>
        <Row>
          <Col span={12}>Model:</Col>
          <Col span={12}>
            <Select
              disabled={loading}
              value={resultSelected?.model}
              style={{ width: 150 }}
              onChange={(value) => handleResultSelectChange(value, 'model')}
              options={resultsData}
            />
          </Col>
        </Row>
        <Row>
          <Col span={12}>Step:</Col>
          <Col span={12}>
            <Select
              disabled={loading}
              style={{ width: 150 }}
              onChange={(value) => handleResultSelectChange(value, 'step')}
              value={resultSelected?.step}
              options={stepData}
            />
          </Col>
        </Row>
        <Row>
          <Col span={12}>Field:</Col>
          <Col span={12}>
            <Select
              disabled={loading}
              style={{ width: 150 }}
              onChange={(value) => handleResultSelectChange(value, 'field')}
              allowClear
              value={resultSelected?.field}
              options={fieldData}
            />
          </Col>
        </Row>
        <Row>
          <Col span={12}>Resolved in:</Col>
          <Col span={12}>
            <Select
              disabled={loading}
              style={{ width: 150 }}
              onChange={(value) => handleResultSelectChange(value, 'resolved')}
              allowClear
              value={resultSelected?.resolved}
              options={[{ label: 'Global System', value: 'global' }]}
            />
          </Col>
        </Row>
        <Row>
          <Col span={12}>Components:</Col>
          <Col span={12}>
            <CheckboxGroup
              options={['x', 'y', 'z']}
              value={componentsData}
              onChange={(v) => {
                setComponentsData(v);
              }}
            />
          </Col>
        </Row>
        <Row>
          <Col span={12}>Resultant:</Col>
          <Col span={12}>
            <CheckboxGroup
              options={['x+y', 'x+z', 'y+z', 'x+y+z']}
              value={resultantData}
              onChange={(v) => {
                setResultantData(v);
              }}
            />
          </Col>
        </Row>
        <Button
          loading={loading}
          disabled={applyShow}
          style={{ width: '100px', marginLeft: '100px' }}
          onClick={async () => {
            clearModel();
            setLoading(true);
            createRendreVectorGraph();
          }}
        >
          Apply
        </Button>
      </WrapperStyle>
    </CommandDialog>
  );
}

// 向量
export const cmdVectorGraph: NMToolBaseCommand = {
  id: 'CmdVectorGraph',
  label: 'command.draw.vector-graph',
  icon: 'commands/simu/vectogram',
  create: (label, onClose) => (
    <CmdVectorGraphDialog
      title={i18n.t(label)}
      onClose={onClose}
    />
  ),
};
